<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import SunComponent from './SunComponent.vue'
import QuestionBox from './QuestionBox.vue'
import WarnIcon from './icons/WarnIcon.vue'
import LadderIcon from './icons/LadderIcon.vue'
import GeneralButton from './GeneralButton.vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import formatDate from '@/utils/formatDate'
import { removeLogin } from '@/utils/auth'
import showMsg from '@/utils/showMsg'
import showCoin from '@/utils/showCoin'
import BackgroundImage from './BackgroundImage.vue'
import CoinIcon from '@/components/icons/CoinIcon.vue'
import fetchCoin from '@/utils/fetchCoin'

const count = defineModel('count', { type: Number })

const fraction = ref(0)
const coins = ref(0)
const questionBoxTop = ref('')
const questionBoxBottom = ref('15%')
const questionBoxRight = ref('50%')
const questionBoxTransform = ref('translateX(50%)')
// 如果是拐弯之后的那就是 top 5%和 right 10%，如果是未拐弯的就是 bottom 60%和 right 50%，再加上一个 translateX(50%)
// 一开始用 bottom 和 right 和 translateX
const route = useRoute()
const router = useRouter()
const startTime = ref('')
const endTime = ref('')
const dialogueId = ref()
const questions = ref([])
const correctCount = ref(0)
const currentScore = ref(0)
const control = ref()
const windowCenter = ref()
const nowTrain = ref('train')
const train = ref()
const train2 = ref()
const locomotive = ref()
const locomotive2 = ref()
const fuel = ref()
const wagon = ref()
const tail = ref()
const center = ref()
const question = ref([])
const options = ref([])
const rightOption = ref()
const windowWidth = ref(window.innerWidth)
const animationArea = ref()
const questionStage = ref('locomotive')
const showQuestionBox = ref(false)
// 车厢部分
// locomotive 火车头
// fuel 燃油车厢
// wagon 货车车厢
// converter 转换器
// tail 火车尾
// end 结束
let intervalId = null

const submit = async () => {
  endTime.value = formatDate(new Date())
  try {
    console.warn('------------------')
    console.log(startTime.value)
    console.log(endTime.value)
    console.log(dialogueId.value)
    console.warn('------------------')
    // 获取一下 connections 里面正确的数量
    // 正确的数量
    // 所得积分，正确加一分，错误减一分，最少为 0
    console.log('正确的数量', correctCount.value)
    console.log('所得积分', currentScore.value)
    console.warn('------------------')
    // 请求添加游戏记录
    const response = await axios.post(
      '/api/north/record',
      {
        part: 2,
        difficulty: parseInt(route.query.difficulty),
        fraction: parseInt(fraction.value),
        rightNum: parseInt(correctCount.value),
        allNum: 5,
        dialogueId: dialogueId.value,
        beginTime: startTime.value,
        endTime: endTime.value
      },
      {
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }
    )
    console.log(response.data)
  } catch (e) {
    console.log(e)
  }
}

const fetchNewQuestions = async () => {
  try {
    const response = await axios.get('/api/north/stem/ques/p2', {
      headers: {
        Authorization: localStorage.getItem('token')
      },
      params: {
        difficulty: route.query.difficulty
      }
    })
    console.log(response)
    const { code } = response.data
    if (code === 401) {
      showMsg({
        type: 'error',
        msg: '登录过期，请重新登录',
        duration: 1000,
        onClose: () => {
          removeLogin()
          router.push({ name: 'login' })
        }
      })
    } else if (code === 200) {
      const { data } = response.data
      console.log(data)
      if (!data) {
        showMsg({
          type: 'error',
          msg: `今天的 PART2 ${route.query.difficulty === '0' ? '简单' : route.query.difficulty === '1' ? '中等' : '困难'}已经完成啦，小朋友明天再来吧`,
          duration: 1000,
          onClose: () => {
            router.push({ name: 'game-select' })
          }
        })
      } else {
        startTime.value = formatDate(new Date())
        console.log(startTime.value)
        dialogueId.value = data[0].dialogueId
        console.log('dialogueId', dialogueId.value)
        questions.value = data.map((item) => {
          let stem = item.stem.replace(/程序/g, '大山').replace(/儿童/g, '你')
          return {
            ...item,
            sentences: stem.split('\n').filter((i) => i)
          }
        })
      }
    } else throw new Error()
  } catch (e) {
    console.log(e)
    showMsg({
      type: 'error',
      msg: '网络错误，请稍后重试',
      duration: 1000,
      onClose: () => {
        router.push({ name: 'game-select' })
      }
    })
  }
}

const updateWidth = () => {
  windowWidth.value = window.innerWidth
}

const handleStop = (el) => {
  if (nowTrain.value === 'train') {
    train.value.style.animationPlayState = 'paused'
  } else {
    train2.value.getAnimations()[0].pause()
  }
  showQuestionBox.value = true
  if (el) {
    el.classList.add('inner-shadow')
  }
}

const handleStart = () => {
  showQuestionBox.value = false
  if (nowTrain.value === 'train') {
    train.value.style.animationPlayState = 'running'
    questionBoxTop.value = ''
    questionBoxRight.value = '50%'
    questionBoxBottom.value = '15%'
  } else {
    train2.value.getAnimations()[0].play()
    questionBoxTop.value = '5%'
    questionBoxRight.value = '10%'
    questionBoxBottom.value = ''
    questionBoxTransform.value = ''
  }
  if (locomotive.value) {
    locomotive.value.classList.remove('inner-shadow')
  }
  if (fuel.value) {
    fuel.value.classList.remove('inner-shadow')
  }
  if (wagon.value) {
    wagon.value.classList.remove('inner-shadow')
  }
  if (tail.value) {
    tail.value.classList.remove('inner-shadow')
  }
}

const checkPosition = () => {
  if (!locomotive.value || !fuel.value) return
  const screenCenter = windowWidth.value / 2
  let el
  if (questionStage.value === 'locomotive') {
    center.value = locomotive.value.getBoundingClientRect().left + locomotive.value.offsetWidth / 2
    el = locomotive.value
  } else if (questionStage.value === 'fuel') {
    center.value = fuel.value.getBoundingClientRect().left + fuel.value.offsetWidth / 2
    question.value = questions.value[1].sentences
    options.value = questions.value[1].options
    rightOption.value = questions.value[1].rightId
    el = fuel.value
  } else if (questionStage.value === 'wagon') {
    center.value = wagon.value.getBoundingClientRect().left + wagon.value.offsetWidth / 2
    question.value = questions.value[2].sentences
    options.value = questions.value[2].options
    rightOption.value = questions.value[2].rightId
    el = wagon.value
  } else if (questionStage.value === 'converter') {
    center.value = locomotive2.value.getBoundingClientRect().left + locomotive.value.offsetWidth
    question.value = questions.value[3].sentences
    options.value = questions.value[3].options
    rightOption.value = questions.value[3].rightId
  } else if (questionStage.value === 'tail') {
    center.value = tail.value.getBoundingClientRect().left + tail.value.offsetWidth / 2
    question.value = questions.value[4].sentences
    options.value = questions.value[4].options
    rightOption.value = questions.value[4].rightId
    el = tail.value
  }
  if (Math.abs(center.value - screenCenter) < 5 && questionStage.value !== 'end') {
    handleStop(el)
  }
  if (questionStage.value === 'converter' && train.value.getBoundingClientRect().right < 0) {
    control.value.checked = false
    train.value.style.display = 'none'
    nowTrain.value = 'train2'
    questionBoxTop.value = '5%'
    questionBoxRight.value = '10%'
    questionBoxBottom.value = ''
    questionBoxTransform.value = ''
    train2.value.getAnimations()[0].play()
  }
  if (questionStage.value === 'end' && train.value.getBoundingClientRect().right < 0) {
    train.value.style.display = 'none'
  }
}

const updatePosition = () => {
  checkPosition()
  requestAnimationFrame(updatePosition)
}

const handleVisibilityChange = () => {
  if (document.visibilityState === 'hidden') {
    handleStop()
  } else if (document.visibilityState === 'visible') {
    handleStart()
  }
}

watch(questionStage, (newVal, oldVal) => {
  console.log('questionStage', newVal, oldVal)
  handleStart()
})

const next = async () => {
  await submit()
  if (fraction.value > 0) {
    showCoin({ count: fraction.value })
  }
  count.value++
}

onMounted(async () => {
  coins.value = await fetchCoin(2)
  console.log(route.query.difficulty)
  if (!['0', '1', '2'].includes(route.query.difficulty)) {
    router.push({ name: 'game-select' })
  }
  await fetchNewQuestions()
  question.value = questions.value[0].sentences
  options.value = questions.value[0].options
  rightOption.value = questions.value[0].rightId
  console.log('question', question.value)
  console.log('options', options.value)
  console.log('rightOption', rightOption.value)
  control.value.checked = true
  train2.value.getAnimations()[0].pause()
  window.addEventListener('resize', updateWidth)
  document.addEventListener('visibilitychange', handleVisibilityChange)
  requestAnimationFrame(updatePosition)
  intervalId = setInterval(checkPosition, 100)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateWidth)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  if (intervalId) {
    clearInterval(intervalId)
  }
})
</script>

<template>
  <div class="container">
    <div
      style="
        position: absolute;
        top: 0;
        right: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 100;
      "
    >
      <coin-icon :size="64" />
      <span style="font-size: 36px; margin-left: 8px; color: white">{{
        coins + fraction < 0 ? '0' : coins + fraction
      }}</span>
    </div>
    <background-image />
    <sun-component class="sun" style="z-index: 100" />
    <div
      v-show="showQuestionBox"
      :style="{
        position: 'absolute',
        top: `${questionBoxTop}`,
        right: `${questionBoxRight}`,
        bottom: `${questionBoxBottom}`,
        transform: `${questionBoxTransform}`,
        zIndex: '100',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center'
      }"
    >
      <question-box
        v-model:correctCount="correctCount"
        v-model:currentScore="currentScore"
        v-model:questionStage="questionStage"
        v-model:fraction="fraction"
        :question="question"
        :options="options"
        :rightOption="rightOption"
      />
    </div>
    <general-button
      v-if="questionStage === 'end'"
      @click="next"
      style="
        position: absolute;
        width: fit-content;
        margin-top: 2rem;
        bottom: 15%;
        left: 50%;
        transform: translateX(-50%);
        z-index: 100;
      "
      >下一段</general-button
    >
    <div class="animation-area" ref="animationArea">
      <div class="center" ref="windowCenter">
        <div
          style="
            position: absolute;
            top: 0;
            width: 18%;
            height: calc(50vh - 2.6rem);
            background: linear-gradient(#79bcff, #acd7ff 100%);
            z-index: 2;
          "
        ></div>
        <div class="train" ref="train" style="z-index: 1">
          <div class="engine-front" ref="locomotive">
            <div class="chimney">
              <div class="smoke"></div>
              <div class="smoke smoke-2"></div>
              <div class="smoke smoke-3"></div>
              <div class="smoke smoke-4"></div>
            </div>
          </div>
          <div class="engine-body"></div>
          <div class="compartment fuel-compartment" ref="fuel">
            <warn-icon :size="48" />
            <ladder-icon :size="60" />
          </div>
          <div class="compartment wagon-compartment" ref="wagon">
            <div class="compartment-window"></div>
          </div>
          <div class="compartment tail-compartment">
            <div class="compartment-no-window"></div>
            <div class="tail"></div>
          </div>
          <div class="wheel-holder">
            <div class="wheel"></div>
            <div class="wheel wheel-2">
              <div class="wheel-joint"></div>
              <div class="wheel-joint wheel-joint-2"></div>
            </div>
            <div class="wheel wheel-3"></div>
            <div class="wheel wheel-4"></div>
            <div class="wheel wheel-5"></div>
            <div class="wheel wheel-6"></div>
            <div class="wheel wheel-7"></div>
            <div class="wheel wheel-8"></div>
            <div class="wheel wheel-9"></div>
          </div>
        </div>
        <label
          class="switch"
          style="position: absolute; bottom: calc(50vh + 3.1rem); right: 70%; z-index: 1"
        >
          <input type="checkbox" ref="control" />
          <span class="toggle"> </span>
        </label>
        <div class="bridge"></div>
        <div
          style="
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: calc(50vh - 2.6rem);
            background: linear-gradient(#79bcff, #acd7ff 100%);
          "
        ></div>
        <div
          style="
            position: relative;
            top: calc(50% + 2.6rem);
            right: 80vw;
            transform: rotate(45deg) scaleX(-1);
            width: 200vw;
            z-index: 1;
          "
        >
          <div class="train-2" ref="train2" style="z-index: 1">
            <div class="engine-front" ref="locomotive2">
              <div class="chimney">
                <div class="smoke"></div>
                <div class="smoke smoke-2"></div>
                <div class="smoke smoke-3"></div>
                <div class="smoke smoke-4"></div>
              </div>
            </div>
            <div class="engine-body"></div>
            <div class="compartment fuel-compartment">
              <warn-icon :size="48" />
              <ladder-icon :size="60" />
            </div>
            <div class="compartment wagon-compartment">
              <div class="compartment-window"></div>
            </div>
            <div class="compartment tail-compartment" ref="tail">
              <div class="compartment-no-window"></div>
              <div class="tail"></div>
            </div>
            <div class="wheel-holder">
              <div class="wheel"></div>
              <div class="wheel wheel-2">
                <div class="wheel-joint"></div>
                <div class="wheel-joint wheel-joint-2"></div>
              </div>
              <div class="wheel wheel-3"></div>
              <div class="wheel wheel-4"></div>
              <div class="wheel wheel-5"></div>
              <div class="wheel wheel-6"></div>
              <div class="wheel wheel-7"></div>
              <div class="wheel wheel-8"></div>
              <div class="wheel wheel-9"></div>
            </div>
          </div>
          <div class="bridge" style="z-index: 0"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import '@/styles/train.css';

.sun {
  position: absolute;
  top: 10%;
  left: 20%;
}

.inner-shadow {
  position: absolute;
  z-index: 0;
  background-color: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 20px 10px rgba(255, 255, 255, 0.5);
  box-shadow:
    0 0 80px 40px rgba(255, 255, 0, 0.5),
    0 0 160px 80px rgba(255, 255, 0, 0.3),
    0 0 240px 120px rgba(255, 255, 0, 0.1);
}

@keyframes rotate45 {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(45deg);
  }
}

/* The switch - the box around the slider */
.switch {
  font-size: 17px;
  position: relative;
  display: inline-block;
  width: 3.5em;
  height: 2em;
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle {
  position: relative;
  display: flex;
  width: 3.8em;
  height: 1em;
  background-color: rgb(165, 165, 165);
  justify-content: center;
}

.toggle::before {
  content: '';
  position: absolute;
  z-index: -1;
  width: 1em;
  height: 3em;
  margin-bottom: 0.5em;
  bottom: 0;
  background-color: rgb(153, 104, 39);
  box-shadow: 0 -1em 0 0 rgb(165, 165, 165);
  transform-origin: bottom;
  transform: rotateZ(-30deg);
  transition: transform 150ms;
}

.switch input:checked + .toggle::before {
  transform: rotateZ(30deg);
}

.switch input:checked + .toggle {
  box-shadow: 0 -1em 2em 0 rgb(230, 111, 111);
}
</style>
